package com.ifnk.portaljava.dapWeb.dapweb;

/*
 * 主要完成XML格式的处理：时间格式的转换，CDR属性的增加。
 * 及处理完后的XML内容的输出
 * */
public class CDR {
	public String proxCdrXmlToWwwCdrXml(int number, String cdrXml)
			throws Exception {
//		Document document = null;
//		String xmlString = null;
		String str_StartTime;
		String str_StartTime_s;
//		try{
//		document = DocumentHelper.parseText(cdrXml);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
		
		int insertIndex = cdrXml.indexOf("</CDR>");
		int startTimeIndexBegin = cdrXml.indexOf("<StartTime>");
		int startTimeIndexEnd = cdrXml.indexOf("</StartTime>");
		int reportTimeIndexBegin = cdrXml.indexOf("<ReportTime>");
		int reportTimeIndexEnd = cdrXml.indexOf("</ReportTime>");
		
		if(insertIndex != -1 && startTimeIndexBegin != -1 && startTimeIndexEnd != -1 && reportTimeIndexBegin != -1 && reportTimeIndexEnd != -1) {
//			cdrXml = cdrXml.substring(0,insertIndex);
//			cdrXml = cdrXml+"<id>"+number+"</id></CDR>";
			
			str_StartTime = cdrXml.substring(startTimeIndexBegin+11, startTimeIndexEnd);
			int index = str_StartTime.lastIndexOf(" ");
			str_StartTime_s = str_StartTime.substring(index + 1);
			str_StartTime = str_StartTime.substring(0, index);
			str_StartTime = timeString(str_StartTime);
			
			String cdrXml_ = cdrXml.substring(0,startTimeIndexBegin);
			cdrXml = cdrXml_ + "<StartTime>" + str_StartTime +"</StartTime><StartTime_S>"+str_StartTime_s+"</StartTime_S>"+
					cdrXml.substring(startTimeIndexEnd+12,cdrXml.length());
			
			String reportTime = cdrXml.substring(reportTimeIndexBegin+12, reportTimeIndexEnd);
			int index2 = reportTime.lastIndexOf(" ");
			//如果是1970年则转换成空
			if(!"0".equals(reportTime.substring(index2 + 1))) {
				reportTime = reportTime.substring(0, index2);
				reportTime = timeString(reportTime);
			} else {
				reportTime = "";
			}
			cdrXml_ = cdrXml.substring(0,reportTimeIndexBegin);
			cdrXml = cdrXml_ + "<ReportTime>" + reportTime + "</ReportTime>" + 
					cdrXml.substring(reportTimeIndexEnd+13,cdrXml.length());
		} else {
			String error = "cdrxml has not </CDR> or <StartTime> or </StartTime> or <ReportTime> or </ReportTime>";
			throw new Exception(error);
		}
		return cdrXml;
	}

	private String timeString(String time) {
		int index = time.lastIndexOf('.');
		if (index <0)
			return time;
		String str = time.substring(index + 1);
		time = time.substring(0, index + 1);
		for (int i=str.length(); i<3; i++) {
			str = "0" + str;
		}
		time = time + str;
		return time;
	}
}